package com.dxy;

import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Properties;

@Slf4j
public class ConfigUtil {

    private static final Properties prop;

    static {
        try {
            prop = loadConfigProperties();
        } catch (Exception e) {
            System.out.println("加载配置出错: ");
            throw new RuntimeException(e);
        }
    }

    private static Properties loadConfigProperties() throws Exception {
        final String EXTERNAL_CONFIG_PATH = "config" + File.separator + "application.properties";
        final String CLASSPATH_CONFIG_PATH = "/application.properties";
        Properties prop = new Properties();

        // 尝试加载外部配置
        File externalConfig = new File(System.getProperty("user.dir"), EXTERNAL_CONFIG_PATH);

        try (InputStream input = new FileInputStream(externalConfig)) {
            prop.load(input);
            System.out.println("加载external配置...");
            return prop;
        } catch (FileNotFoundException ignored) {

        }

        // 回退到classpath配置
        try (InputStream input = Main.class.getResourceAsStream(CLASSPATH_CONFIG_PATH)) {
            prop.load(input);
            System.out.println("加载classpath配置...");
            return prop;
        }
    }

    public static Properties getProperties(){
        return prop;
    }

    public static void main(String[] args) {
        System.out.println("db.url: " + prop.getProperty("db.url"));
//        log.info("lombok slf4j");
        log.info("test log info");
    }
}
